package com.ruoyi.project.service.impl;

import java.math.BigDecimal;
import java.util.Arrays;
import java.util.List;

import com.ruoyi.common.exception.ServiceException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.ruoyi.project.mapper.MedicalInsuranceInfoMapper;
import com.ruoyi.project.domain.MedicalInsuranceInfo;
import com.ruoyi.project.service.IMedicalInsuranceInfoService;
import org.springframework.util.CollectionUtils;
import org.slf4j.Logger;


/**
 * 医疗保险Service业务层处理
 * 
 * @author xiao6ming6
 * @date 2025-05-15
 */
@Service
public class MedicalInsuranceInfoServiceImpl implements IMedicalInsuranceInfoService 
{
    @Autowired
    private MedicalInsuranceInfoMapper medicalInsuranceInfoMapper;
    private static final Logger log = org.slf4j.LoggerFactory.getLogger(MedicalInsuranceInfoServiceImpl.class);


    /**
     * 查询医疗保险
     * 
     * @param id 医疗保险主键
     * @return 医疗保险
     */
    @Override
    public MedicalInsuranceInfo selectMedicalInsuranceInfoById(String id)
    {
        return medicalInsuranceInfoMapper.selectMedicalInsuranceInfoById(id);
    }

    /**
     * 查询医疗保险列表
     * 
     * @param medicalInsuranceInfo 医疗保险
     * @return 医疗保险
     */
    @Override
    public List<MedicalInsuranceInfo> selectMedicalInsuranceInfoList(MedicalInsuranceInfo medicalInsuranceInfo)
    {
        return medicalInsuranceInfoMapper.selectMedicalInsuranceInfoList(medicalInsuranceInfo);
    }

    /**
     * 新增医疗保险
     * 
     * @param medicalInsuranceInfo 医疗保险
     * @return 结果
     */
    @Override
    public int insertMedicalInsuranceInfo(MedicalInsuranceInfo medicalInsuranceInfo) {
        validateMedicalInsuranceInfo(medicalInsuranceInfo); // 调用验证方法
        return medicalInsuranceInfoMapper.insertMedicalInsuranceInfo(medicalInsuranceInfo);
    }

    /**
     * 修改医疗保险
     * 
     * @param medicalInsuranceInfo 医疗保险
     * @return 结果
     */
    @Override
    public int updateMedicalInsuranceInfo(MedicalInsuranceInfo medicalInsuranceInfo) {
        validateMedicalInsuranceInfo(medicalInsuranceInfo); // 调用验证方法
        return medicalInsuranceInfoMapper.updateMedicalInsuranceInfo(medicalInsuranceInfo);
    }

    /**
     * 批量删除医疗保险
     * 
     * @param ids 需要删除的医疗保险主键
     * @return 结果
     */
    @Override
    public int deleteMedicalInsuranceInfoByIds(String[] ids)
    {
        return medicalInsuranceInfoMapper.deleteMedicalInsuranceInfoByIds(ids);
    }

    /**
     * 删除医疗保险信息
     * 
     * @param id 医疗保险主键
     * @return 结果
     */
    @Override
    public int deleteMedicalInsuranceInfoById(String id)
    {
        return medicalInsuranceInfoMapper.deleteMedicalInsuranceInfoById(id);
    }
    /**
     * 验证医疗保险信息
     */
    private void validateMedicalInsuranceInfo(MedicalInsuranceInfo medicalInsuranceInfo) {
        try {
            // 验证个人缴费比例
            BigDecimal rate = medicalInsuranceInfo.getPersonalPaymentRate();
            if (rate != null) {
                if (rate.scale() == 0 && rate.compareTo(new BigDecimal("100")) <= 0) {
                    rate = rate.divide(new BigDecimal("100"));
                    medicalInsuranceInfo.setPersonalPaymentRate(rate);
                } else if (rate.compareTo(BigDecimal.ZERO) < 0 || rate.compareTo(BigDecimal.ONE) > 0) {
                    throw new IllegalArgumentException("个人缴费比例必须在0到1之间");
                }
            }

            // 验证单位实缴金额
            BigDecimal employerPayment = medicalInsuranceInfo.getEmployerActualPayment();
            if (employerPayment != null && employerPayment.compareTo(BigDecimal.ZERO) < 0) {
                throw new IllegalArgumentException("单位实缴金额不能为负数");
            }

            // 验证个人实缴金额
            BigDecimal personalPayment = medicalInsuranceInfo.getPersonalActualPayment();
            if (personalPayment != null && personalPayment.compareTo(BigDecimal.ZERO) < 0) {
                throw new IllegalArgumentException("个人实缴金额不能为负数");
            }

            // 验证缴费标识
            String paymentStatus = medicalInsuranceInfo.getPaymentStatus();
            if (paymentStatus != null && !Arrays.asList("已缴费", "未缴费", "部分缴费").contains(paymentStatus)) {
                throw new IllegalArgumentException("缴费标识无效");
            }
        } catch (Exception e) {
            throw new IllegalArgumentException("数据异常，请检查输入数据: " + e.getMessage(), e);
        }
    }
    /**
     * 导入医疗保险信息
     */
    @Override
    public String importMedicalInsurance(List<MedicalInsuranceInfo> medicalInsuranceList, boolean updateSupport) {
        if (CollectionUtils.isEmpty(medicalInsuranceList)) {
            throw new ServiceException("导入数据不能为空！");
        }
        int successNum = 0;
        int failureNum = 0;
        StringBuilder successMsg = new StringBuilder();
        StringBuilder failureMsg = new StringBuilder();
        for (MedicalInsuranceInfo medicalInsurance : medicalInsuranceList) {
            try {
                // 检查数据是否已存在
                MedicalInsuranceInfo exist = medicalInsuranceInfoMapper.selectMedicalInsuranceInfoById(medicalInsurance.getId());
                if (exist == null) {
                    medicalInsuranceInfoMapper.insertMedicalInsuranceInfo(medicalInsurance);
                    successNum++;
                    successMsg.append("<br/>" + successNum + "、缴费明细ID " + medicalInsurance.getId() + " 导入成功");
                } else if (updateSupport) {
                    medicalInsuranceInfoMapper.updateMedicalInsuranceInfo(medicalInsurance);
                    successNum++;
                    successMsg.append("<br/>" + successNum + "、缴费明细ID " + medicalInsurance.getId() + " 更新成功");
                } else {
                    failureNum++;
                    failureMsg.append("<br/>" + failureNum + "、缴费明细ID " + medicalInsurance.getId() + " 已存在");
                }
            } catch (Exception e) {
                failureNum++;
                String msg = "<br/>" + failureNum + "、缴费明细ID " + medicalInsurance.getId() + " 导入失败：";
                failureMsg.append(msg + e.getMessage());
                log.error(msg, e);
            }
        }
        if (failureNum > 0) {
            failureMsg.insert(0, "很抱歉，导入失败！共 " + failureNum + " 条数据格式不正确，错误如下：");
            throw new ServiceException(failureMsg.toString());
        } else {
            successMsg.insert(0, "恭喜您，数据已全部导入成功！共 " + successNum + " 条，数据如下：");
        }
        return successMsg.toString();
    }


}
